package web.factory;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import util.RedXml;
import factotyService.ServiceProcess;

public class CreateTranceFactory {
	//请求处理配置文件路径
	private static String TRANCEXMLPATH = "factoryInf/createTrance.xml";
	//项目代号
	private static String SYS_NO = "blog";
	/**
	 * @param req
	 * @param res
	 * @return
	 * @throws IOException
	 * @throws JSONException
	 * 获取对应请求的处理类对象，反射实现动态创建对象执行构造
	 */
	public static ServiceProcess getTrance(HttpServletRequest req, HttpServletResponse res) 
			throws IOException, JSONException{
		
		String path = req.getServletPath();
		path = path.substring(1,path.length());
		
		Map<String,String> map = new HashMap<String,String>();//读xml内容到map存储
		
		RedXml redXml = null;
		try {
			redXml = new RedXml(TRANCEXMLPATH, SYS_NO);
		} catch (Exception e1) {
			System.out.println("读取xml配置文件异常");
			e1.printStackTrace();
		}
		map = redXml.getTrancePath();
		String trancePath = "";
		trancePath = map.get(path);
		Class<?> cls = null;
		try {
			//动态加载类信息
			cls = Class.forName(trancePath);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		Constructor<?> con = null;
		ServiceProcess sp = null;
		try {
			//获取带参构造
			con = cls.getConstructor(HttpServletRequest.class,HttpServletResponse.class);
			//执行构造并返回对象
			sp = (ServiceProcess)con.newInstance(req,res);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
		return sp;
		
	}
}
